import os
import shutil
import json
from pathlib import Path

def sync_directories(src_dir: str, dst_dir: str):
    """
    同步两个目录的内容，将 src_dir 的内容同步到 dst_dir
    
    Args:
        src_dir: 源目录路径 (python-office)
        dst_dir: 目标目录路径 (auto-office)
    """
    print(f"Syncing from {src_dir} to {dst_dir}")
    
    # 确保目标目录存在
    os.makedirs(dst_dir, exist_ok=True)
    
    # 保存 display_names.json 如果存在
    display_names_path = os.path.join(dst_dir, 'display_names.json')
    display_names_backup = None
    if os.path.exists(display_names_path):
        with open(display_names_path, 'r', encoding='utf-8') as f:
            display_names_backup = json.load(f)
    
    # 清空目标目录（保留 .gitignore）
    gitignore_path = os.path.join(dst_dir, '.gitignore')
    gitignore_content = None
    if os.path.exists(gitignore_path):
        with open(gitignore_path, 'r', encoding='utf-8') as f:
            gitignore_content = f.read()
    
    # 删除目标目录中的所有内容（除了.gitignore）
    for item in os.listdir(dst_dir):
        if item != '.gitignore':
            item_path = os.path.join(dst_dir, item)
            try:
                if os.path.isfile(item_path):
                    os.unlink(item_path)
                elif os.path.isdir(item_path):
                    shutil.rmtree(item_path)
            except Exception as e:
                print(f"Error removing {item_path}: {e}")
    
    # 复制源目录内容到目标目录
    def copy_directory(src: str, dst: str):
        for item in os.listdir(src):
            s = os.path.join(src, item)
            d = os.path.join(dst, item)
            
            # 跳过 __pycache__ 目录和 .pyc 文件
            if item == '__pycache__' or item.endswith('.pyc'):
                continue
                
            try:
                if os.path.isdir(s):
                    shutil.copytree(s, d, dirs_exist_ok=True)
                else:
                    shutil.copy2(s, d)
            except Exception as e:
                print(f"Error copying {s} to {d}: {e}")
    
    copy_directory(src_dir, dst_dir)
    
    # 恢复 .gitignore
    if gitignore_content:
        with open(gitignore_path, 'w', encoding='utf-8') as f:
            f.write(gitignore_content)
    
    # 恢复 display_names.json
    if display_names_backup:
        with open(display_names_path, 'w', encoding='utf-8') as f:
            json.dump(display_names_backup, f, ensure_ascii=False, indent=2)
    
    print("Sync completed!")
    
    # 打印同步的文件统计
    src_files = sum([len(files) for _, _, files in os.walk(src_dir)])
    dst_files = sum([len(files) for _, _, files in os.walk(dst_dir)])
    print(f"\nStatistics:")
    print(f"Source files: {src_files}")
    print(f"Destination files: {dst_files}")

def main():
    # 获取脚本所在目录
    script_dir = Path(__file__).parent.parent
    
    # 构建源目录和目标目录的路径
    src_dir = script_dir / 'resources' / 'files' / 'python-office'
    dst_dir = script_dir / 'resources' / 'files' / 'auto-office'
    
    # 检查源目录是否存在
    if not src_dir.exists():
        print(f"Error: Source directory not found: {src_dir}")
        return
    
    # 执行同步
    sync_directories(str(src_dir), str(dst_dir))

if __name__ == '__main__':
    main() 